package com.atguigu.tingshu.search.runnable;

import com.atguigu.tingshu.search.factory.ScheduleTaskThreadPoolFactory;
import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * <a href="https://www.shallowrecall.top/">Recall`Blog</a></br>
 * <a href="https://github.com/ShallowRecall">GitHub</a>
 *
 * @author Recall
 * @createTime 2025/03/27 09:45
 **/
public class RebuildBloomFilterRunnable implements Runnable{

    private RedissonClient redissonClient;
    private StringRedisTemplate redisTemplate;
    private ItemServiceImpl itemServiceImpl;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    public RebuildBloomFilterRunnable(RedissonClient redissonClient, StringRedisTemplate redisTemplate, ItemServiceImpl itemServiceImpl) {
        this.redissonClient = redissonClient;
        this.redisTemplate = redisTemplate;
        this.itemServiceImpl = itemServiceImpl;
    }

    @Override
    public void run() {
        RBloomFilter<Object> albumInfoBloomFilterNew = redissonClient.getBloomFilter("albumInfoBloomFilterNew");

        boolean b = albumInfoBloomFilterNew.tryInit(1000000, 0.001);

        List<Long> albumInfoIdList = itemServiceImpl.getAlbumInfoIdList();

        albumInfoIdList.stream().forEach(albumInfoBloomFilterNew::add);

        String script = " redis.call(\"del\",KEYS[1])" +
                "  redis.call(\"del\",KEYS[2])" +
                "  redis.call(\"rename\",KEYS[3],KEYS[1])" +
                "  redis.call(\"rename\",KEYS[4],KEYS[2]) return 0";
        List<String> asList = Arrays.asList("albumIdBloomFilter", "{albumIdBloomFilter}:config", "albumInfoBloomFilterNew", "{albumInfoBloomFilterNew}:config");
        long execute = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), asList);
        if (execute == 0){
            logger.info("老布隆已经被删除，新布隆上线...");
        }

        /*ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
        scheduledExecutorService.schedule(this,10, TimeUnit.SECONDS); // 延时任务+嵌套任务本身 从而实现定时的效果。【Nacos源码】*/

        ScheduleTaskThreadPoolFactory.getInstance().execute(this,7L, TimeUnit.DAYS);

    }
}
